//
//  HMStatusViewModel.swift
//  weibo10
//
//  Created by mac on 15/10/21.
//  Copyright © 2015年 itheima. All rights reserved.
//

import Foundation
import SDWebImage

class HMStatusListViewModel {
    /// 微博数据数组
    lazy var statusList = [HMStatusViewModel]()
    func loadStatus(isPullup isPullup: Bool, finished:(isSuccess:Bool) -> ()){
        let since_id = isPullup ? 0 : (statusList.first?.status.id ?? 0)
        let max_id = isPullup ? (statusList.last?.status.id ?? 0) : 0
        NetworkTools.sharedTools.loadStatus(since_id: since_id, max_id: max_id) { (result, error) -> () in
            if error != nil {
                print("出错了")
                return
            }
            
            guard let array = result?["statuses"] as? [[String: AnyObject]] else {
                print("格式不对")
                finished(isSuccess: false)
                return
            }
            var dataList = [HMStatusViewModel]()
            for dict in array {
                
                dataList.append(HMStatusViewModel(status: HMStatus(dict: dict)))
            }
            if max_id > 0 {
                self.statusList = self.statusList + dataList
            } else {
                self.statusList = dataList + self.statusList
            }
            // 缓存单张图片
            self.cacheSingleImage(dataList, finished: finished)
        }

    }
    /// 缓存图片
    private func cacheSingleImage(dataList: [HMStatusViewModel],finished:(isSuccess:Bool) -> ()) {
        // 0. 创建调度组
        let group = dispatch_group_create()
        // 缓存数据长度
        var dataLength = 0
        // 1.遍历数组
        for vm in dataList {
            // 1> 只缓存单张图片
            if vm.thumbnailUrls?.count != 1 {
                continue
            }
            // 2> 获取单张图片的url
            let url = vm.thumbnailUrls![0]
            // 入组 -监听后续的block
            dispatch_group_enter(group)
            // 3> 下载图片
            SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (image, _, _, _, _) -> Void in
                if let img = image, let data = UIImagePNGRepresentation(img) {
                    dataLength += data.length
                }
                // 出组
                dispatch_group_leave(group)
            })
        }
        // 监听调度组完成
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            finished(isSuccess: true)
        }
    }
}